import RPi.GPIO as GPIO
import dht11
import time
from collections import deque
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

def GetTagData():
    result = instance.read()
    if result.is_valid():
        t= result.temperature
        h= result.humidity
        return t,h        
    else:
        pass


# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

# read data using pin 16
instance = dht11.DHT11(pin = 16)

t_tag="Temperature"
h_tag="Humidity"
t = deque()
h = deque()

columns = ()
col_labels = ['Tag', 'Unit', 'Value']
table_vals = [[t_tag,"C",""],
              [h_tag,"%",""]]

fig, ax = plt.subplots()
ax.set_title("The Simple Monitor:DHT11")
ln_t, = plt.plot([], [], 'r-o')
ln_h, = plt.plot([], [], 'b-*')
str_cursecond=str(time.localtime(time.time()).tm_sec)   
time_text = ax.text(0.5, 90, "")

tbl = ax.table(cellText=table_vals,
               colLabels=col_labels,
               colWidths=[0.2] * 3,
               cellLoc='center',
               loc='best')

def init():
    ax.set_xlim(0, 10)
    ax.set_ylim(0, 90)
    return ln_t,ln_h

def update(frames):
    # blocking io -> unresponsive_monitor
    # GetTagData
    try:
        cur_t, cur_h =GetTagData()
        if len(t) <= 10:
            t.append(cur_t)
            h.append(cur_h)
        else:
            t.popleft()
            t.append(cur_t)
            h.popleft()
            h.append(cur_h)
    except:
        if len(t) <= 10:
            t.append(None)
            h.append(None)
        else:
            t.popleft()
            t.append(None)
            h.popleft()
            h.append(None)

    str_curtime=time.strftime("%F %H:%M:%S", time.localtime(time.time()))
    time_text.set_text("Time:"+str_curtime)
        
    try:
       table_vals = [[t_tag,"C",str(cur_t)],
                  [h_tag,"%",str(cur_h)],]
    except: 
        table_vals = [[t_tag,"C","-"],
                  [h_tag,"%","-"]]
        
    tbl = ax.table(cellText=table_vals,
               colLabels=col_labels,
               colWidths=[0.2] *3,
               cellLoc='center',loc='best')

    ln_t.set_xdata(np.arange(len(t)))
    ln_t.set_ydata(np.array(t))
    ln_h.set_xdata(np.arange(len(h)))
    ln_h.set_ydata(np.array(h))
    return ln_t,ln_h,time_text, tbl
    
ani = FuncAnimation(fig, update,init_func=init, blit=True,interval=1000)
plt.show()